package com.example.wechat.util;

import android.content.Context;
import android.content.SharedPreferences;
import com.example.wechat.model.User;
import com.google.gson.Gson;

public class UserManager {
    private static final String PREF_NAME = "user_pref";
    private static final String KEY_USER = "current_user";
    private static UserManager instance;
    private SharedPreferences preferences;
    private User currentUser;

    private UserManager(Context context) {
        preferences = context.getApplicationContext()
                .getSharedPreferences(PREF_NAME, Context.MODE_PRIVATE);
        loadUser();
    }

    public static synchronized UserManager getInstance() {
        if (instance == null) {
            throw new IllegalStateException("UserManager not initialized");
        }
        return instance;
    }

    public static void init(Context context) {
        if (instance == null) {
            instance = new UserManager(context);
        }
    }

    private void loadUser() {
        String userJson = preferences.getString(KEY_USER, null);
        if (userJson != null) {
            currentUser = new Gson().fromJson(userJson, User.class);
        } else {
            // 创建默认用户
            currentUser = new User();
            currentUser.setNickname("微信用户");
            currentUser.setWechatId("wxid_" + System.currentTimeMillis());
            currentUser.setGender("男");
            currentUser.setRegion("中国");
            currentUser.setSignature("这个人很懒，什么都没留下");
            saveUser();
        }
    }

    public void saveUser() {
        if (currentUser != null) {
            String userJson = new Gson().toJson(currentUser);
            preferences.edit().putString(KEY_USER, userJson).apply();
        }
    }

    public User getCurrentUser() {
        return currentUser;
    }

    public void updateUser(User user) {
        this.currentUser = user;
        saveUser();
    }

    public void logout() {
        currentUser = null;
        preferences.edit().remove(KEY_USER).apply();
    }
} 